﻿#include "msgsocket.h"
#include "globalvars.h"

#include <QStringBuilder>

MsgSocket::MsgSocket(QTcpSocket *socket, QObject *parent):
    QObject(parent)
{
    qDebug() << "MsgSocket::MsgSocket";
    m_tcpBlockSize = 0;

    m_socket = socket;
    connect(m_socket, SIGNAL(disconnected()),
            m_socket, SLOT(deleteLater()));
    connect(m_socket, SIGNAL(readyRead()),
            this, SLOT(slotReadyRead()));
}

MsgSocket::~MsgSocket()
{

}

void MsgSocket::slotReadyRead()
{
    qDebug() << "MsgSocket::slotReadyRead()";
    QDataStream in(m_socket);
    in.setVersion(QDataStream::Qt_4_6);

    if(m_tcpBlockSize == 0)
    {
        if(m_socket->bytesAvailable()<sizeof(quint16))
            return;

        in >> m_tcpBlockSize;
    }

    if(m_socket->bytesAvailable() < m_tcpBlockSize)
        return;

    QString msg;
    in >> msg;
    qDebug() << "Server Recv: " << msg;

    GlobalVars::g_msgQueue.enqueue(msg);
    m_tcpBlockSize = 0;
}

bool MsgSocket::slotSendMsg(QString msg)
{
    QByteArray buffer;
    QDataStream out(&buffer, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);

    out << (quint16)0;
    out << msg;
    out.device()->seek(0);
    out << (quint16)(buffer.size() - sizeof(quint16));

    qDebug() << "Server Send: " << msg;
    return m_socket->write(buffer);
}

